package common;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringBufferInputStream;
import java.lang.reflect.Constructor;
import java.nio.Buffer;

import sun.java2d.pipe.BufferedBufImgOps;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class FileTransferMessage extends Message {

	private String filename;
	private String extension;
	private String PATH = "/Downloads/tmp";
	
	public FileTransferMessage(String pathname, String destination) throws IOException {
		// load file to get content and filename
		File file = new File(pathname);
		this.filename = file.getName();
		String content = this.encodeToBase64(file);
		this.setContent(content);
		this.setContenttype(MessageContentType.FILE);
		this.setRecipient(destination);
		
	}
	
	public String getFilePath() throws IOException{
		return this.decodeFromBase64(this.getContent());
	}

	private String encodeToBase64(File file) throws IOException{
		FileInputStream in = new FileInputStream(file);
		OutputStream out = new ByteArrayOutputStream();
		BASE64Encoder encoder = new BASE64Encoder();
		encoder.encode(in, out);
		return out.toString();
	}

	private String decodeFromBase64(String content) throws IOException{	
		StringBufferInputStream in = new StringBufferInputStream(content);
		BASE64Decoder decoder = new BASE64Decoder();
		byte[] filebytes;
		filebytes = decoder.decodeBuffer(in);
		
	    try{
	        // Create file 
	    	FileOutputStream fos = new FileOutputStream(this.PATH + this.filename);
		    fos.write(filebytes);
		    fos.close(); 
			
	        }catch (Exception e){
	          System.err.println("Error: " + e.getMessage());
	        }
		return this.filename;
	}

	public void setFilename(String filename) {
		this.filename = filename;
	}

	public String getFilename() {
		return filename;
	}
	
	public String getParsedCommandString(){
		// SEND---recipient---file---this.getContent()---filename
		StringBuilder sb = new StringBuilder();
		String seperator = "---";
		sb.append("SEND"+seperator);
		if(this.sender != null){
			sb.append(this.getSender());
		} else{
			sb.append("all");
		}
		sb.append(this.getContenttype().toString()+seperator);
		sb.append(this.getContent()+seperator);
		sb.append(this.getFilename());
		return sb.toString();
	}
	
	public void parseFromCommandString(Object msg){
		String seperator = "---";
		// prses a server string like
		// SEND---recipient---file---this.getContent()---filename
		String serverAnswer = msg.toString();
		String answer[] = serverAnswer.split("---");
		content = answer[3];
	    filename = answer[4];
		
		this.setContent(content);
		this.setFilename(filename);
	}

	
}
